(function(window) {
	var browser = {
	        versions : function() {
	            var u = navigator.userAgent, app = navigator.appVersion;
	            return {//移动终端浏览器版本信息
	                trident : u.indexOf('Trident') > -1, //IE内核
	                presto : u.indexOf('Presto') > -1, //opera内核
	                webKit : u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
	                gecko : u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
	                mobile : !!u.match(/AppleWebKit.*Mobile.*/)
	                || !!u.match(/AppleWebKit/), //是否为移动终端
	                ios : !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
	                android : u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
	                iPhone : u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
	                iPad : u.indexOf('iPad') > -1, //是否iPad
	                webApp : u.indexOf('Safari') == -1
	                //是否web应该程序，没有头部与底部
	            };
	        }(),
	        language : (navigator.browserLanguage || navigator.language).toLowerCase()
	};
	
	window.share_browser = browser;
})(window);

jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		var path = options.path ? '; path=' + options.path : '';
		var domain = options.domain ? '; domain=' + options.domain : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};
var Common = function() {

	return {

		layerDialogStyle : 'width:'
				+ (document.documentElement.clientWidth * 0.95) + 'px;',
		//layerFullStyle : 'width:100%; height:'
		//		+ parent.document.documentElement.clientHeight
		//		+ 'px; border:none;',
		layerFullStyle : 'width:100%; height:'+document.documentElement.clientHeight+'px; border:none;',

		storage : function(key, value) {
			localStorage.setItem(key, value);
		},

		getStorage : function(key) {
			return localStorage.getItem(key);
		},

		storageJson : function(key, value) {
			localStorage.setItem(key, JSON.stringify(value));
		},

		getJsonStorage : function(key) {
			return JSON.parse(localStorage.getItem(key));
		},

		overflowY : function(enable) {
			if (enable) {
				//document.body.parentNode.style.overflowY = "auto";
				$('body', parent.document).css('overflow', 'auto')
			} else {
				//document.body.parentNode.style.overflowY = "hidden";//隐藏且禁用
				$('body', parent.document).css('overflow', 'hidden')
			}
		},

		location : function(callback) {
			if (navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(function(position) {
					Common.showPosition(position, callback);
				}, function(error) {
					var errorMsg = messages.unknownError;
					switch (error.code) {
						case error.PERMISSION_DENIED :
							errorMsg = messages.refuseLocating;
							break;
						case error.POSITION_UNAVAILABLE :
							errorMsg = messages.unavailable;
							break;
						case error.TIMEOUT :
							errorMsg = messages.timeoutLocation;
							break;
						case error.UNKNOWN_ERROR :
							errorMsg = messages.unavailableGPS;
							break;
					}
					if (callback) {
						callback({
							error : errorMsg
						});
					}
				});
			} else {
				Page.notice(messages.unsupportGPS);
			}
		},

		showPosition : function(position, callback) {
			var latlon = position.coords.latitude + ','
					+ position.coords.longitude;

			//google
			var url = 'http://maps.google.cn/maps/api/geocode/json?latlng='
					+ latlon + '&language=CN';
			$.ajax({
				type : "GET",
				url : url,
				success : function(json) {
					if (json.status == 'OK') {
						var results = json.results;
						$.each(results, function(index, array) {
							if (index == 0) {
								if (callback) {
									callback({
										latitude : position.coords.latitude,
										longitude : position.coords.longitude,
										address : array['formatted_address']
									});
								}
							}
						});
					}
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					if (callback) {
						callback({
							error : messages.failedLocation
						});
					}
				}
			});
		}

	}
}();


var Page = function() {
	var strPath = window.document.location.pathname;
	var contextPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);

	return {

		serverPath: '',

		contextPath: contextPath,

		storeToken: function(timestamp, nonce, digest) {
			Common.storageJson("_TOKEN", {_timestamp: timestamp, _nonce: nonce, _digest: digest});
			$.cookie('_timestamp', timestamp);
			$.cookie('_nonce', nonce);
			$.cookie('_digest', digest);
		},
		getToken : function() {
			return Common.getJsonStorage("_TOKEN");
		},

		storeUser : function(user) {
			Common.storageJson("_USER", user);
			$.cookie('userId', user.id);
		},

		getUser : function() {
			var user = Common.getJsonStorage("_USER");
			if (!user) {
				user = {
					id : '',
					name : ''
				}
			}
			return user;
		},

		getUserA : function() {
			var user = Page.getUser();
			var userToken = localStorage.getItem("userTonken");
			var lang = localStorage.getItem("lang");
			return '<a uid="' + user.id + '" href="' + Page.contextPath + '/u/' + user.id + '.do?userToken='+userToken+'&lang='+lang+'">'
					+ user.name + '</a>';
		},

		notice : function(message) {
			parent.layer.open({
				content : message,
				time : 1
			});
		},

		confirm : function(message, yesCallback) {
			parent.layer.open({
				content : message,
				btn : [messages.yes, messages.cancel],
				shadeClose : false,
				anim : false,
				yes : function(index) {
					if (yesCallback) {
						parent.layer.close(index)
						yesCallback();
					}
				},
				no : function() {
				}
			});
		},

		ajax : function(type, url, params, isFilter, callback, errorCallback) {
			var loadi = null;
			if (isFilter) {
				loadi = layer.open({
					type : 2,
					content : ''
				});
			}
			$.ajax({
				type : type,
				url : contextPath + url,
				data : params,
				cache : false,
				beforeSend : function(request) {
					//request.setRequestHeader("userId", Page.getUser().id);
					//var token = Page.getToken();
					//if (token) {
					//	request.setRequestHeader("_timestamp", token._timestamp);
					//	request.setRequestHeader("_nonce", token._nonce);
					//	request.setRequestHeader("_digest", token._digest);
					//}
				},
				success : function(response) {
					console.log("请求成功!");
					if (loadi != null) {
						layer.close(loadi);
					}
					if (response.resultCode == '1') { //成功
						if (callback) {
							callback(response);
						}
					} else if (errorCallback) {
						errorCallback(response)
					} else {
						Page.notice(response.resultDes);
					}
				},
				error : function(msg) {
					console.log("请求失败！");
					console.log(msg);
					if (loadi != null) {
						layer.close(loadi);
					}
					Page.notice(messages.networkUnavailable);
				}
			});
		},

		ajaxPost : function(url, params, callback, errorCallback) {
			Page.ajax('POST', url, params, true, callback, errorCallback);
		},

		ajaxPostQuiet : function(url, params, callback, errorCallback) {
			Page.ajax('POST', url, params, false, callback, errorCallback);
		},

		ajaxGet : function(url, params, callback, errorCallback) {
			Page.ajax('GET', url, params, true, callback, errorCallback);
		},

		ajaxGetQuiet : function(url, params, callback, errorCallback) {
			Page.ajax('GET', url, params, false, callback, errorCallback);
		},

		ajaxPut : function(url, params, callback, errorCallback) {
			if (!params) {
				params = {};
			}
			params._method = 'PUT';
			Page.ajaxPost(url, params, callback, errorCallback);
		},

		ajaxDelete : function(url, params, callback, errorCallback) {
			if (!params) {
				params = {};
			}
			params._method = 'DELETE';
			Page.ajaxGet(url, params, callback, errorCallback);
		},

		ajaxDeleteQuiet : function(url, params, callback, errorCallback) {
			if (!params) {
				params = {};
			}
			params._method = 'DELETE';
			Page.ajaxGetQuiet(url, params, callback, errorCallback);
		},

		getParam : function(str, defaultValue) {
			var rs = new RegExp("(^|)" + str + "=([^&]*)(&|$)", "gi")
					.exec(String(window.document.location.href)), tmp;
			if (tmp = rs)
				return tmp[2];
			return defaultValue;
		},
		insertText : function(obj, str, maxlength) {
			if (maxlength && obj.value.length + str.length > maxlength) {
				//Page.notice(messages.muchWords+"!");
				return;
			}
			if (document.selection) {
				var sel = document.selection.createRange();
				sel.text = str;
			} else if (typeof obj.selectionStart === 'number'
					&& typeof obj.selectionEnd === 'number') {
				var startPos = obj.selectionStart, endPos = obj.selectionEnd, cursorPos = startPos, tmpStr = obj.value;
				obj.value = tmpStr.substring(0, startPos) + str
						+ tmpStr.substring(endPos, tmpStr.length);
				cursorPos += str.length;
				obj.selectionStart = obj.selectionEnd = cursorPos;
			} else {
				obj.value += str;
			}
		},

		onPull: function(callback) {
			$('#wapper-pull').xpull({
				'callback': callback,
				'spinnerTimeout': 0
			});
		},

		resetPull: function() {
			$('#wapper-pull').data('plugin_xpull').reset();
		},

		onMore: function(callback) {
			$(window).scroll(function () {
				var scrollTop = $(this).scrollTop();
				var scrollHeight = $(document).height();
				var windowHeight = $(this).height();
				if (scrollTop + windowHeight == scrollHeight) {
					callback();
				}
			});
		}
	}
}();

var Feed = {

	create : function(container, share) {

		var feed = {};
		feed.share = share;

		feed.bind = function(_container) {
			_container.find('.share').each(function() {
				feed.bindShare($(this));
			});
		}

		feed.bindShare = function(_share) {
			if (!_share.hasClass('share')) {
				return;
			}
			// 详情
			_share.click(function(e) {
				var obj = e.target || e.srcElement;
				var userToken = localStorage.getItem("userTonken");
				var lang = localStorage.getItem("lang");

				if (obj.nodeName == 'VIDEO') {
					//_share.find('video').play();
					//return false;
				} else if (!_share.hasClass('detail')) {// 详情页面不再跳转了
					
					window.location.href = Page.contextPath + '/share/' + _share.attr('id')+'.do?userToken='+userToken+'&lang='+lang;
				}
			});
			// 赞
			_share.find('.like').click(function() {
				if ($(this).hasClass('selected')) {
					feed.share.cancelLike($(this), _share);
				} else {
					feed.share.addLike($(this), _share);
				}
				return false;
			});
			// 评论分享，点击评论按钮或者底部输入栏
			_share.find('.comment').click(
				function() {
					feed.share.comment(messages.comment, _share, Feed.getShareUserId(_share));
					return false;
				});
			// 回复某人
			_share.find('.interact-detail').find(
				'p:gt(1):not(.comment)').click(
				function() {
					var user = $(this).find('a:eq(0)');
					var commentTo = user.attr('uid');
					if (commentTo != Page.getUser().id) {// 点击自己不回复
						feed.share.comment(messages.reply+'@' + user.text(), _share,
							commentTo, $(this).attr('msgId'));
					} else {// 点击自己的评论提示删除
						$(this).find('i.delete').toggle();
					}
					return false;
				});
			_share.find('.interact-detail p .iconfont.delete').click(
				function() {
					feed.share.deleteComment(_share, $(this).parents('p:eq(0)'));
					return false;
				});
			// 分享详情里面，右边回复小按钮
			_share.find('.interact-detail .operate-box').click(
				function() {
					var header = $(this).parent('header');
					var commentTo = header.find('.mod-avatar').attr('uid');
					var commentToName = header.find('.mod-info a').text();

					feed.share.comment(messages.reply+'@'+ commentToName, _share,
						commentTo, header.next('aside').find('p:eq(0)')
							.attr('msgId'));
					return false;
				});
			// 消息里面，右边回复小按钮
			_share.find('.reply').click(
				function() {
					var message = $(this).parents('.share.message');
					var user = Feed.getShareUser(message);

					feed.share.reply(message, user, message.find('header:eq(0)').attr('msgId'), message.find('header').attr('type'));
					return false;
				});
			// 转发
			_share.find('.mod-interact .forward').click(function() {
				//if (_share.find())
				if(typeof _share.attr("original") !== "undefined" && _share.find('.detail .inner a[uId]').length == 0) {
					Page.notice(messages.delShare+'！');
				} else {
					feed.share.forward(_share);
				}
				return false;
			});

			// 图片大图浏览
			_share.find('.detail .wj-img-s').click(function() {
				var $this = $(this);
				var _index = $this.prevAll().length;
				Slide.show($this.parents('.share .detail').find('img'),
					_index);
				return false;
			});
			
//			// 删除
//			_share.find('.delete i').click(function() {
//				Page.confirm(messages.isDel, function() {
//					feed.share.delete(_share);
//				})
//				return false;
//			});
			
			// 删除
			_share.find('.wj-delete').click(function() {
				Page.confirm(messages.isDel, function() {
					feed.share.delete(_share);
				})
				return false;
			});
		}

		feed.bind(container);
		return feed;
	},

	getShareUserId : function(shareNode) {
		var shareUserId = shareNode.children('header').children('.mod-avatar')
				.attr('uid');
		return shareUserId;
	},

	getShareUser : function(shareNode) {
		var header = shareNode.children('header');
		var user = {};
		user.id = header.children('.mod-avatar').attr('uid');
		user.name = header.find('.mod-info a').text();
		return user;
	},

	refreshComments : function(comment, shareNode) {
		if (!comment.refer) {// 回复分享发布者
			shareNode.find('.interact-detail').show();
			shareNode.find('.interact-detail p:last').after(
					'<p class="txt-l comments" msgId="' + comment.msgId + '">'
							+ Page.getUserA() + ': ' + comment.text
							+ '</p>');
			var commentCount = shareNode.find('.mod-interact .comment span').text();
			if(commentCount != messages.comment){
				shareNode.find('.mod-interact .comment span').text(parseInt(commentCount)+1);
			}else{
				shareNode.find('.mod-interact .comment span').text(1);
			}
			
		} else {// 回复某人
			shareNode.find('.interact-detail p:last').after(
					'<p class="txt-l comments" msgId="'
							+ comment.msgId
							+ '">'
							+ Page.getUserA()
							+ messages.reply
							+ shareNode.find(
									'p[msgId="' + comment.refer
											+ '"] a:eq(0)').prop(
									'outerHTML') + ': ' + comment.text
							+ '</p>');
		}
	},

	refreshMessage : function (comment, message) {
		message.find('.interact-detail').append(
			'<p class="txt-l comments" msgId="'
			+ comment.msgId
			+ '">'
			+ Page.getUserA()
			+ messages.reply
			+ message.find(
				'.mod-info > a').prop(
				'outerHTML') + ': ' + comment.text
			+ '</p>');
	}
};

var Share = {

	create : function(container) {

		var friend = Friend.create($('#warpper-friends'));
		var friendGroup = FriendGroup.create(friend);// 好友分组

		var share = {};
		share.textarea = container.find('#txt-publisher');
		share.scope = ShareScope.create(container
				.find('.info-publisher a.scope'), $('#wrapper-scope'), friend,
				friendGroup);
		share.friend = friend;
		// 定位,经度, 纬度
		share.location = false, share.longitude, share.latitude, share.address;
		share.isInit = true;
		container.find('.info-publisher .pos').click(function() {
			var pos = $(this);
			if (share.location) {// 已经定位了
				pos.find('span').html(messages.location);
				share.location = false;
			} else {
				pos.find('span').html(messages.locating+'...');
				if (browser.versions.ios || browser.versions.iPhone || browser.versions.iPad) {
					function connectWebViewJavascriptBridge(callback) {
				        if (window.WebViewJavascriptBridge) {
				            callback(WebViewJavascriptBridge);
				        } else {
				            document.addEventListener(
				                'WebViewJavascriptBridgeReady'
				                , function() {
				                    callback(WebViewJavascriptBridge);
				                },
				                false
				            );
				        }
				    }
					
					connectWebViewJavascriptBridge(function(bridge) {
						if(share.isInit){
							bridge.init(function(message, responseCallback) {
					            var data = {
					                'Javascript Responds': 'Wee!'
					            };
					            responseCallback(data);
					        });
							share.isInit = false;
						}
				        bridge.callHandler('getLocation', {}, function(response) {
				        	if(response.length > 0){
				        		var mapStrJson = $.parseJSON(response);
				        		share.longitude = mapStrJson.longitude;
								share.latitude = mapStrJson.latitude;
				        		var address = mapStrJson.address;
				        		var index = address.indexOf(messages.province);
								if (index > 0) {
									address = address.substring(index + 1);
								}
								share.address = address;
								// 显示的时候不显示市
								index = address.indexOf(messages.city);
								if (index > 0) {
									address = address.substring(index + 1);
								}
								pos.find('span').html(address);
								share.location = true;
				        	}else{
				        		share.location = true;
				        		pos.find('span').html(messages.failedLocation);
				        	}
				        });
				    })
			    }else if (browser.versions.android){
			    	var mapStr = native.getmap();
					if(mapStr.length > 0){
						var mapStrJson = $.parseJSON(mapStr);
		        		share.longitude = mapStrJson.longitude;
						share.latitude = mapStrJson.latitude;
		        		var address = mapStrJson.address;
		        		var index = address.indexOf(messages.province);
						if (index > 0) {
							address = address.substring(index + 1);
						}
						share.address = address;
						// 显示的时候不显示市
						index = address.indexOf(messages.city);
						if (index > 0) {
							address = address.substring(index + 1);
						}
						pos.find('span').html(address);
						share.location = true;
					}else{
						pos.find('span').html(messages.failedLocation);
						share.location = true;
					}
			    }
				/*Common.location(function(position) {
					if (position.error) {
						Page.notice(position.error);
						pos.find('span').html(messages.location);
					} else {
						share.longitude = position.longitude;
						share.latitude = position.latitude;
						var address = position.address;
						var index = address.indexOf(messages.province);
						if (index > 0) {
							address = address.substring(index + 1);
						}
						share.address = address;
						// 显示的时候不显示市
						index = address.indexOf(messages.city);
						if (index > 0) {
							address = address.substring(index + 1);
						}
						pos.find('span').html(address);
						share.location = true;
					}
				});*/
			}
		});
		// 表情
		var face = container.find('.wrapper-face');
		face.find('.content-tab-face i').on(
				'click',
				function() {
					Page.insertText(document.getElementById('txt-publisher'),
							$(this).attr('data-face'), 140);
					$("#txt-publisher").maxlength({
			            counterContainer: $(".txt-publisher-wrapper .max-length"),
			            text: '%left'
			        });
					document.getElementById('txt-publisher').blur();
					//face.hide();
				});

		// @好友
		container.find('.action-publisher i.friend').click(
				function() {
					friend.toSelect(false, function(user, $user) {
						// 选择了好友
						if (window.document.location.href.indexOf('#friend') > 0) {
							Page.insertText(document.getElementById('txt-publisher'), '@' + user.name + ' ', 140);
							// friend.close();
							$("#txt-publisher").maxlength({
					            counterContainer: $(".txt-publisher-wrapper .max-length"),
					            text: '%left'
					        });
							history.back();
							//$user.parents('.layermbox').hide();
						}
					});
				});

		// 表情
		container.find('.action-publisher i.emotion').click(
				function() {
					if (face.is(":hidden")) {
						face.show();
						face.height(container.find('.content-tab-face')
								.height() + 15);
						$('.facewrapper').swipeSlide(
								{
									index : 0,
									continuousScroll : false,
									autoSwipe : false,
									lazyLoad : false,
									callback : function(i) {
										$('.nav-tab-face li').removeClass(
												'current');
										$('.nav-tab-face li:eq(' + i + ')')
												.addClass('current');
									}
								});
					} else {
						face.hide();
					}
				});

		// 转发时是否评论
		container.find('.info-publisher .comment').css('visibility', 'visible')
				.click(function() {
					if ($(this).hasClass('selected')) {
						$(this).removeClass('selected');
					} else {
						$(this).addClass('selected');
					}
				});

		// 开始写分享
		share.write = function() {
			var webuploader = Webuploader.create(container.find('.J-preview'),
					container.find('.module-publisher .statusBar'));
			// 发送按钮事件绑定
			$('.module-topbar .fr').click(function() {
				var params = share.getPostParams();
				params.fileCount = webuploader.fileCount;
				if ($.trim(params.content).length == 0 && $('.uploadList').length < 2) {
					$('#txt-publisher').val(null);
					return;
				}
				var loadi = layer.open({
					type : 2,
					content : ''
				});
				if (webuploader.fileCount > 0) {
					params.type = "02";// 图片
					webuploader.upload($(this), function(files) {
						params.atype = "1";// 图片
						params.files = files.join(',');
						var userToken = localStorage.getItem("userTonken");
						var lang = localStorage.getItem("lang");
						Page.ajaxPost('/share.do?userToken='+userToken+'&lang='+lang, params, function(response) {
							layer.close(loadi);
							Page.notice(messages.sent+'！');
							//location.href = document.referrer;
							location.replace(document.referrer);
						});
					});
				} else {
					var picture = $('.J-preview').find('.uploadList:not(.add-picture)');
					params.type = "01";// 文字
					if (picture.length > 0) {
						var imgs = picture.find('img');
						if (imgs.length > 0) {// Android native上传的
							var files = [];
							$(imgs).each(function() {
								files.push($(this).attr('data-src'));
							});
							params.type = "02";// 图片
							params.atype = "1";// 图片
							params.files = files.join(',');
							params.fileCount = imgs.length;
						} else {
							params.type = "03";// 视频
							params.atype = "2";// 视频
							params.files = picture.find("source:eq(0)").attr('src');
							params.fileCount = 1;
						}
					}
					var userToken = localStorage.getItem("userTonken");
					var lang = localStorage.getItem("lang");
					Page.ajaxPost('/share.do?userToken='+userToken+'&lang='+lang, params, function(response) {
						layer.close(loadi);
						Page.notice(messages.sent+'！');
						//location.href = document.referrer;
						location.replace(document.referrer);
						//history.back();
					});
				}
			});
			return share;
		};

		// 删除
		share.delete = function(shareNode) {
			var shareId = shareNode.attr('id');
			var userToken = localStorage.getItem("userTonken");
			var lang = localStorage.getItem("lang");
			Page.ajaxDelete('/share/' + shareId+'/forDel.do?userToken='+userToken+'&lang='+lang, null, function(response) {
				shareNode.remove();

				// 详情页面需要刷新
				if (window.document.location.href.indexOf('/share/' + shareId) > 0) {
					location.replace(document.referrer);
				}
			});
		},

		// 赞
		share.addLike = function(likeNode, shareNode) {
			var shareUserId = Feed.getShareUserId(shareNode);
			if (!shareUserId) {
				Page.notice(messages.refresh);
				return;
			}
			var userToken = localStorage.getItem("userTonken");
			var lang = localStorage.getItem("lang");
			Page.ajaxPostQuiet('/' + shareNode.attr('id') + '/like.do?userToken='+userToken+'&lang='+lang, {
				commentTo : shareUserId
			}, function() {
				likeNode.addClass('selected');
				var input = likeNode.find('input'), liked = input.val();
				var user = Page.getUser();
				var userToken = localStorage.getItem("userTonken");
				var lang = localStorage.getItem("lang");
				var likes = shareNode.find('p.likes');
				if (liked >= 1) {// 其他人已经赞过
					input.val(parseInt(liked) + 1);
					likes.append('<span>,</span><a uid="' + user.id + '" href="' + Page.contextPath + '/u/' + user.id + '.do?userToken='+userToken+'&lang='+lang+'">' + user.name + '</a>');// 加逗号
				} else {// 第一次赞
					input.val('1');
					if(shareNode.find('.interact-detail p').length >= 3){
						likes.addClass("wj-likes");
					}
					likes.parents(".interact-detail").removeClass("wj-interact-details-none");
					likes.append('<a uid="' + user.id + '" href="' + Page.contextPath + '/u/' + user.id + '.do?userToken='+userToken+'&lang='+lang+'">' + user.name + '</a>');
					shareNode.find('p.likes i').show();
				}

			});
		};
		share.cancelLike = function(likeNode, shareNode) {
			var userToken = localStorage.getItem("userTonken");
			var lang = localStorage.getItem("lang");
			Page.ajaxDeleteQuiet('/' + shareNode.attr('id') + '/cancelLike.do?userToken='+userToken+'&lang='+lang, null,
					function() {
						likeNode.removeClass('selected');
						var input = likeNode.find('input'), liked = input.val();
						var user = Page.getUser();

						if (liked == '1') {// 只有一人赞过
							input.val("0");
							shareNode.find('p.likes a[uid="' + user.id + '"]').remove();
//							shareNode.find('p.likes').empty(); // 清空容器
							shareNode.find('p.likes i').hide();
							shareNode.find('.likes').removeClass("wj-likes");
							if(shareNode.find('.interact-detail a').length == 0){
								shareNode.find('.interact-detail').addClass("wj-interact-details-none");
							}
						} else {
							input.val(parseInt(liked) - 1);
							var u = shareNode.find('p.likes a[uid="' + user.id + '"]');
							u.prev('span:eq(0)').remove();
							u.remove();
						}
					});
		};

		// 获取通用参数
		share.getPostParams = function() {
			var params = {};
			params.content = share.textarea.val();
			params.scope = share.scope.scopeId;
			params.groupId = share.scope.groupId;
			if (share.location) {
				params.longitude = share.longitude;
				params.latitude = share.latitude;
				params.address = share.address;
			}
			return params;
		}

		// 删除评论
		share.deleteComment = function(shareNode, commentNode) {
			var userToken = localStorage.getItem("userTonken");
			var lang = localStorage.getItem("lang");
			Page.confirm(messages.isDel, function() {
				var shareId = shareNode.attr('id');
				Page.ajaxDelete('/comment/' + commentNode.attr('msgId')+'.do?userToken='+userToken+'&lang='+lang, null, function(response) {
					Page.notice(messages.deleted+'！');
					// 详情页面需要刷新
					if (window.document.location.href.indexOf('/share/' + shareId) > 0
							&& commentNode.prev('p').length == 0) {
						location.replace(location.href);
					} else {
						commentNode.remove();
						var commentCount = shareNode.find('.mod-interact .comment span').text();
						if(commentCount == 1){
							shareNode.find('.mod-interact .comment span').text(messages.comment);
						}else{
							shareNode.find('.mod-interact .comment span').text(parseInt(commentCount)-1);
						}
					}
				});
			});
		},

		share.layerId = -1;
		// 评论
		share.comment = function(title, shareNode, commentTo, referMsgId) {
			if (!commentTo || commentTo == "") {
				Page.notice(messages.refresh);
				return;
			}
			share.textarea.val('').attr('placeholder', messages.comment+'...');
			container.find('.info-publisher').hide();
			// 发送按钮事件
			container.find('a.send').unbind("click").click(function() {
				saveComment(share, shareNode, commentTo, referMsgId);
			});
			// 弹窗
			Common.overflowY(false);
			share.layerId = layer.open({
				title : title,
				shadeClose : false,
				anim : false,
				content : '',
				className : 'modal',
				style : Common.layerDialogStyle,
				success : function(elem) {
					container.show().appendTo($(elem).find('.layermcont'));
					$('.maxlength').html(140);
				},
				end : function() {
					share.layerId = -1;
					if (window.document.location.href.indexOf('#comment') > 0) {
						history.back();
					}
					Common.overflowY(true);
				}
			});
			history.pushState(null, "", "#comment");
		};
		// 保存回复
		function saveComment(share, shareNode, commentTo, referMsgId) {
			var params = share.getPostParams();
			if ($.trim(params.content).length == 0) {
				$('#txt-publisher').val(null);
				return;
			}
			var shareUserId = Feed.getShareUserId(shareNode);
			if (!shareUserId || (!referMsgId && shareUserId != commentTo)) {
				Page.notice(messages.refresh);
				return;
			}
			params.commentTo = commentTo;
			params.refer = referMsgId;
			if (shareNode.hasClass('detail')) {// 分享详情评论，需分组
				params.group = '1';
			}
			var userToken = localStorage.getItem("userTonken");
			var lang = localStorage.getItem("lang");
			Page.ajaxPost('/' + shareNode.attr('id') + '/comment.do?userToken='+userToken+'&lang='+lang, params,
					function(resp) {
						if (shareNode.hasClass('detail')) {// 分享详情评论，需分组
							history.back();
							reload(resp.data);
						} else {// 首页评论
							history.back();
							Feed.refreshComments(resp.data, shareNode);
						}
					});
		}

		// 转发
		share.forward = function(shareNode) {
			share.textarea.val('').attr('placeholder',messages.repeat+'...');
			container.find('.info-publisher').show();
			var shareUser = Feed.getShareUser(shareNode);

			// 发送按钮事件
			container.find('a.send').unbind("click").click(function() {
				saveForward(share, shareNode);
			});

			Common.overflowY(false);
			share.layerId = layer.open({
				title : messages.repeat+'@' + shareUser.name,
				shadeClose : false,
				anim : false,
				content : '',
				className : 'modal',
				style : Common.layerDialogStyle,
				success : function(elem) {
					container.show().appendTo($(elem).find('.layermcont'));
					$('.maxlength').html(140);
				},
				end : function() {
					share.layerId = -1;
					if (window.document.location.href.indexOf('#forward') > 0) {
						history.back();
					}
					Common.overflowY(true);
				}
			});
			history.pushState(null, "", "#forward");
		}
		// 保存转发
		function saveForward(share, shareNode) {
			var params = share.getPostParams();
			params.original = shareNode.attr('original');
			// 转发时同时回复
			params.isComment = container.find(
					'.info-publisher a.comment .selected').is(":hidden")
					? '0'
					: '1';
			
			if(params.isComment == 1) {
				if ($.trim(params.content).length == 0) {
					$('#txt-publisher').val(null);
					$('#txt-publisher').focus();
					return;
				}
			}
			
			params.commentTo = Feed.getShareUserId(shareNode);
			var userToken = localStorage.getItem("userTonken");
			var lang = localStorage.getItem("lang");
			Page.ajaxPost('/' + shareNode.attr('id') + '/forward.do?userToken='+userToken+'&lang='+lang, params,
					function(resp) {
						history.back();
						// 首页重新加载
						if (window.document.location.href.indexOf('feed') > 0) {
							reload();
						} else {
							var userToken = localStorage.getItem("userTonken");
							var lang = localStorage.getItem("lang");
							var user = Page.getUser();
							var forward = shareNode.find('.interact-detail .forward');
							var forwardCount = forward.find('a').length;
							shareNode.find('.mod-interact .forward span').text(forwardCount + 1);
							if (forwardCount > 0) {
								forward.append('<span>,</span><a uid="' + user.id + '" href="' + Page.contextPath + '/u/' + user.id + '.do?userToken='+userToken+'&lang='+lang+'">' + user.name + '</a>');// 加逗号
							} else {
								forward.append('<a uid="' + user.id + '" href="' + Page.contextPath + '/u/' + user.id + '.do?userToken='+userToken+'&lang='+lang+'">' + user.name + '</a>');
								forward.find('i').show();
							}
						}
					});
		}

		// 评论
		share.reply = function(message, to, referMsgId, type) {
			share.textarea.val('').attr('placeholder',messages.reply+'...');
			container.find('.info-publisher').hide();
			// 发送按钮事件
			container.find('a.send').unbind("click").click(function() {
				saveReply(message, to, referMsgId, type);
			});
			// 弹窗
			Common.overflowY(false);
			share.layerId = layer.open({
				title : messages.reply + to.name,
				shadeClose : false,
				anim : false,
				content : '',
				className : 'modal',
				style : Common.layerDialogStyle,
				success : function(elem) {
					container.show().appendTo($(elem).find('.layermcont'));
					$('.maxlength').html(140);
				},
				end : function() {
					share.layerId = -1;
					if (window.document.location.href.indexOf('#reply') > 0) {
						history.back();
					}
					Common.overflowY(true);
				}
			});
			history.pushState(null, "", "#reply");
		};
		// 保存回复
		function saveReply(message, to, referMsgId, type) {
			var params = share.getPostParams();
			if (params.content.length == 0) {
				return;
			}
			if (type != '3') {// 消息页面回复点赞或者转发
				params.content = /*'@' + to.name + ' ' + */params.content;
			}
			params.commentTo = to.id;
			params.refer = referMsgId;
			var userToken = localStorage.getItem("userTonken");
			var lang = localStorage.getItem("lang");
			Page.ajaxPost('/' + message.find('.refer').attr('id') + '/comment.do?userToken='+userToken+'&lang='+lang, params,
				function(resp) {
					history.back();
					Feed.refreshMessage(resp.data, message);
				});
		}

		// 弹窗事件
		share.bindPopstate = function() {
			// 页面前进后退
			$(window).on("popstate", function(event) {
				if (friend.isShow()) { // 当前页面，如果好友显示，那么后退肯定先隐藏
					friend.close();
				} else if (friendGroup.isShow()) { // 编辑分组显示了
					friendGroup.close();
				} else if (share.scope.isShow()) { // 选择分享范围显示了
					share.scope.close();
				} else {
					layer.close(share.layerId);
				}
			});
			return share;
		};

		// 页面前进后退
		share.bindPopstate();
		return share;
	}
};

var ShareScope = {

	create : function(picker, container, friend, friendGroup) {

		var scope = {};
		scope.container = container;
		container.remove();
		scope.layerId = -1;

		scope.scopeId = "public";// 默认公开
		scope.groupId = "";// 选择的好友组

		var enableModule, disableModule, enable_part, disable_part;
		enableModule = scope.container.find('#enable');
		disableModule = scope.container.find('#disable');
		enable_part = scope.container.find('#enable-part');
		disable_part = scope.container.find('#disable-part');

		// 确定
		scope.container.find('a[name="complete"]').click(function() {
			scope.selectFinish();
		});
		// 选择分享范围大类
		scope.container.find('section.auth-list').click(function() {
			scope.select($(this));
		});
		// 选择好友分组
		scope.clickUserSection = function(sections) {
			$(sections).click(
					function() {
						var scopeId = $(this).parent('.auth-list').prev(
								'section').attr('id');
						scope.select($(this), scopeId);
					});
			// 查看好友组详情
			$(sections).find('.more').click(
					function() {
						var section = $(this).parent('section');
						friendGroup.edit(section.attr('id'), function(type,
								group, groups) {
							if (type == 'update') {
								var div = section.find('.title');
								div.find('span:eq(0)').text(group.groupName);
								div.find('span:eq(1)').text(group.userCount);
							} else if (type == 'delete') {
								section.remove();
								scope.select(scope.container.find('#public'));// 选择公开
							}
							FriendGroup.storageFriendGroups(groups);
						});
						//return false;
					});
		};
		scope.clickUserSection(scope.container.find('div.auth-list').find(
				'section:not(:first)'));

		// 添加分组
		var addBtn = scope.container.find('section.user-list.add');
		addBtn.click(function() {
			var scopeId = $(this).parent('.auth-list').prev('section').attr(
					'id');
			friend.toSelect(true, function(users) {
				var params = {};
				params.groupType = scopeId;
				params.users = JSON.stringify(users);
				var userToken = localStorage.getItem("userTonken");
				var lang = localStorage.getItem("lang");
				Page.ajaxPost('/userGroup.do?userToken='+userToken+'&lang='+lang, params, function(resp) {
					FriendGroup.storageFriendGroups(resp.data);
					var groups = resp.data[scopeId];
					var group = groups[groups.length - 1];
					// 添加到范围分组里面
					var tpl = document.getElementById('scope-tpl').innerHTML;
					laytpl(tpl).render([group], function(html) {
						var section;
						if (scopeId == "enable") {
							enable_part.append(html);
							section = enable_part.find('section:last');
						} else {
							disable_part.append(html);
							section = disable_part.find('section:last');
						}
						scope.clickUserSection(section);
						scope.select(section, scopeId);
					});

					// 返回
					scope.scopeId = scopeId;
					scope.groupId = group.groupId;
					picker.children('div i').hide();
					picker.children('div i.' + scopeId).show();
					//picker.children('div').removeClass().addClass(scopeId);
					picker.find('span').text(group.groupName);

					// friend.close();
					scope.close();
					history.go(-2);// 返回到写分享页面
				});
			});
		});

		// 去选择分享范围
		picker.click(function() {
			Common.overflowY(false);
			scope.layerId = parent.layer.open({
				type : 1,
				content : '',
				style : Common.layerFullStyle,
				success : function(elem) {
					scope.container.show()
							.appendTo($(elem).find('.layermcont'));

				},
				end : function() {
					scope.layerId = -1;
					//history.back();
					Common.overflowY(true);
					//scope.container.clone(true).hide().appendTo($('body'));
				}
			});
			history.pushState(null, "", "#module");
		});

		// 选择分享范围
		scope.select = function(section, scopeId) {
			section = $(section);
			var id = section.attr('id');
			if (id == 'enable') {// 部分可见
				enable_part.toggle();
				section.find('.more .open').toggle().prev('i.close').toggle();
			} else if (id == 'disable') {// 部分不可见
				disable_part.toggle();
				section.find('.more .open').toggle().prev('i.close').toggle();
			} else if (id == 'public' || id == 'private') {
				scope.container.find('div.selected').removeClass('selected');
				section.find('div.select').addClass('selected');
			} else {
				scope.container.find('div.selected').removeClass('selected');
				section.find('div.select').addClass('selected');
				if (scopeId == 'enable') {
					enableModule.find('div.select').addClass('selected');
				} else {
					disableModule.find('div.select').addClass('selected');
				}
			}
		};

		// 确定选择分享范围
		scope.selectFinish = function() {
			var selectScopes = scope.container.find('section div.selected');
			if (selectScopes.length == 1) {// 公开或者私有
				var section = selectScopes.parents('section');
				scope.scopeId = section.attr('id');
				picker.children('div i').hide();
				picker.children('div i.' + scope.scopeId).show();
				//picker.children('div').removeClass().addClass(scope.scopeId);
				picker.find('span').text(section.find('.title').html());
			} else {
				var section = $(selectScopes[0]).parents('section');
				var usersSection = $(selectScopes[1]).parents('section');
				scope.scopeId = section.attr('id');
				scope.groupId = usersSection.attr('id');
				picker.children('div i').hide();
				picker.children('div i.' + scope.scopeId).show();
				//picker.children('div').removeClass().addClass(scope.scopeId);
				picker.find('span').text(
						usersSection.find('.title span:eq(0)').html());
			}
			// scope.close();
			history.back();
		};
		scope.isShow = function() {
			return scope.layerId != -1;
		};
		scope.hide = function() {
			container.hide();
		};
		scope.close = function() {
			parent.layer.close(scope.layerId);
		};

		return scope;
	}
};

var FriendGroup = {

	_GROUP_KEY : '_USER_GROUPS',

	create : function(friend) {

		var group = {};
		group.layerId = -1;
		group.friends;
		group.container = $('#wrapper-group');
		var textarea = group.container.find('.group-textarea'), addBtn = group.container
				.find('.user-list header.add'), deleteBtn = group.container
				.find('.user-list header.delete');
		deleteBtn.hide();// 先隐藏

		var tpl = '{{# for(var i = 0, len = d.length; i < len; i++){ var friend = d[i];}}'
				+ '<header class="friend">'
				+ '<a class="mod-avatar" uid="{{friend.id}}"><div class="avatar"><img src="{{friend.avatar}}" onerror="$(this).attr(\'src\',\'http://123.57.249.184/i/defaultAvatar/moren_icon.png\')"></div></a>'
				+ '<div class="name">{{friend.name}}</div><span class="delete"></span><i class="iconfont delete hid">&#xe618;</i></header>'
				+ '{{# } }}';

		addBtn.click(function() {
			friend.toSelect(true, function(users, $user) {
				// 去掉重复
				var newUsers = [];
				$(users).each(
						function(index, user) {
							if (group.container.find('.mod-avatar[uid="'
									+ user.id + '"]').length == 0) {
								newUsers.push(user);
							}
						});
				addFriend(newUsers);
				//history.back();
			});
		});

		deleteBtn.click(function() {
			group.container.find('.user-list header.friend .delete').click(
					function() {
						$(this).parent('header').remove();
						var firends = group.container
								.find('.user-list header.friend');
						if (firends.length == 0) {
							deleteBtn.hide();
						}
					}).toggle();
		});
		// 删除组
		group.container.find('.delete-buttone').click(
				function() {
					var userToken = localStorage.getItem("userTonken");
					var lang = localStorage.getItem("lang");
					Page.confirm(messages.isDel, function() {
						Page.ajaxDelete('/userGroup/' + group.groupId+'/del.do?userToken='+userToken+'&lang='+lang, null,
								function(resp) {
									history.back();
									if (group.editCallback) {
										var grp = {};
										grp.groupId = group.groupId;
										group.editCallback('delete', grp,
												resp.data);
									}
								})
					});
				});

		// 保存
		group.container.find('[name="save"]').click(
				function() {
					var uids = [];
					var avatars = group.container
							.find('.user-list header.friend .mod-avatar');
					$(avatars).each(function() {
						uids.push($(this).attr('uid'));
					});
					FriendGroup.updateGroup(group.groupId, textarea.val(),
							uids, group.editCallback);
				});

		group.edit = function(groupId, callback) {
			group.groupId = groupId;
			group.editCallback = callback;

			Common.overflowY(false);
			group.layerId = parent.layer.open({
				type : 1,
				content : '',
				style : Common.layerFullStyle,
				success : function(elem) {
					group.container.find('.user-list header.friend').remove();
					group.container.show()
							.appendTo($(elem).find('.layermcont'));
					group.query(groupId);// 查询
				},
				end : function() {
					group.layerId = -1;
					//history.back();
					Common.overflowY(true);
				}
			});
			history.pushState(null, "", "#group");
		};
		group.isShow = function() {
			return group.layerId != -1;
		}
		group.close = function() {
			parent.layer.close(group.layerId);
		};

		group.query = function(groupId) {
			var userToken = localStorage.getItem("userTonken");
			var lang = localStorage.getItem("lang");
			Page.ajaxGet('/userGroup/' + groupId+'.do?userToken='+userToken+'&lang='+lang, null, function(response) {
				var grp = response.data;
				textarea.val(grp.groupName);
				addFriend(grp.users);
			});
		}
		// 添加好友
		function addFriend(users) {
			laytpl(tpl).render(users, function(html) {
				addBtn.before(html);
				deleteBtn.show();
			});
		}

		return group;
	},

	updateGroup : function(groupId, groupName, uids, callback) {
		if (groupName.length == 0) {
			Page.notice(messages.enterTagName+'！');
			return false;
		}
		if (uids.length == 0) {
			Page.notice(messages.selectContacts+'！');
			return false;
		}
		var params = {};
		params.groupName = groupName;
		params.uids = uids.join(',');
		var userToken = localStorage.getItem("userTonken");
		var lang = localStorage.getItem("lang");
		Page.ajaxPut('/userGroup/' + groupId+'/update.do?userToken='+userToken+'&lang='+lang, params, function(resp) {
			history.back();
			if (callback) {
				var grp = {};
				grp.groupId = groupId;
				grp.groupName = groupName;
				grp.userCount = uids.length;
				callback('update', grp, resp.data);
			}
		});
	},

	getFriendGroups : function() {
		return Common.getJsonStorage(FriendGroup._GROUP_KEY);
	},

	storageFriendGroups : function(userGroup) {
		Common.storageJson(FriendGroup._GROUP_KEY, userGroup);
	}
};

var Friend = {

	create : function(container) {
		var friend = {};
		friend.layerId = -1;

		friend.container = container;
		var completeBtn = container.find('[name="complete"]');
		var searchInput = container.find("input.search"); // 输入框
		var searchButton = container.find(".j_searchButton"); // 搜索按钮
		var deleteIcon = container.find(".search-pos-pop .clear"); // 删除
		var friendsDefault = container.find("#friends-default"); // 搜索结果
		var searchResult = container.find("#friends-result"); // 搜索结果

		// 确定按钮
		completeBtn.click(function() {
			friend.select();// 多选
		});
		// 输入框焦点事件
		searchInput.focus(function() {
			friendsDefault.hide();
			searchResult.show();
			searchButton.show();
		});

		// 删除输入
		deleteIcon.click(function() {
			searchInput.val("");
			searchResult.empty();
			deleteIcon.hide();
			searchButton.text(messages.cancel);
		});

		// 输入监听
		searchInput.bind('input propertychange', function() {
			if (searchInput.val().length > 0) {
				deleteIcon.show();
				searchButton.text(messages.search);
			} else {
				deleteIcon.hide();
				searchButton.text(messages.cancel);
				searchResult.empty();
			}
		});

		// 搜索按钮
		searchButton.click(function() {
			if (searchButton.text() == messages.cancel) {
				friendsDefault.show();
				searchResult.hide();
				searchButton.hide();
				searchResult.empty();
				searchInput.val("");
				deleteIcon.hide();
			} else { // 搜索
				searchResult.empty();
				searchButton.text(messages.cancel);
				friendsDefault.find(
						"section span:contains(" + searchInput.val() + ")")
						.each(
								function() {
									searchResult.append($(this).parents(
											"section").clone(true));
								});
			}
		});

		// 选择好友
		container.find('section.user-list').click(function() {
			var sel = $(this).find('div.select');
			if (!friend.multiple) { // 单选
				friend.select($(this));
			} else { // 多选
				if (sel.hasClass('selected')) {
					sel.removeClass('selected');
				} else {
					sel.addClass('selected');
				}
			}
		});

		// 清空
		friend.init = function() {
			if (!friend.multiple) { // 单选
				completeBtn.hide();
			} else {
				completeBtn.show();
			}
			container.find('section div.select').removeClass('selected');
			deleteIcon.click();
			searchButton.click();
		}

		// 如果窗口本身是顶层窗口，parent属性返回的是对自身的引用
		friend.toSelect = function(multiple, callback) {
			friend.multiple = multiple;
			friend._callback = callback;// 回调函数

			Common.overflowY(false);
			friend.layerId = parent.layer.open({
				type : 1,
				content : '',
				style : Common.layerFullStyle,
				//className:'myFinds',
				success : function(elem) {
					friend.container.show().appendTo(
							$(elem).find('.layermcont'));

					friend.init();
				},
				end : function() {
					friend.layerId = -1;
					//history.back();
					Common.overflowY(true);
				}
			});
			history.pushState(null, "", "#friend");
		};

		// 选择，单选直接返回
		friend.select = function(section) {
			if (friend._callback) {
				if (!friend.multiple) { // 单选
					friend._callback(getUser(section), section);
				} else {
					var users = [];
					friend.container.find('section.user-list div.selected')
							.each(function() {
								var userSection = $(this).parents('section');
								users.push(getUser(userSection));
							});
					if (users.length == 0) {
						Page.notice(messages.selectContacts);
						return false;
					}
					friend._callback(users);
					parent.layer.close(friend.layerId);
				}
			}
		};
		// 获取用户信息
		function getUser(section) {
			var user = {};
			user.id = section.attr('uid');
			user.name = section.find('span').text();
			user.avatar = section.find('.avatar img').attr('src');
			return user;
		};
		friend.isShow = function() {
			return friend.layerId != -1;
		};
		friend.close = function() {
			parent.layer.close(friend.layerId);
		};

		return friend;
	}
};

var Webuploader = {

	create : function($queue, $statusBar) {// 图片容器,状态栏，包括进度

		var $progress = $statusBar.find('.progress').hide();

		var webuploader = {};

		// 上传按钮
		webuploader.$upload;
		// 添加的文件数量
		webuploader.fileCount = 0;

		// 添加的文件总大小
		webuploader.fileSize = 0;

		// 优化retina, 在retina下这个值是2
		var _ratio = window.devicePixelRatio || 1,

		// 缩略图大小
		_thumbnailWidth = 110 * _ratio, _thumbnailHeight = 110 * _ratio;

		// 可能有pedding, ready, uploading, confirm, done.
		webuploader.state = 'pedding';

		// 所有文件的进度信息，key为file id
		webuploader.percentages = {};

		webuploader.addbutton = $('<div class="uploadList add-picture"><img src="'+basePath+'/resource/images/add_share.png"/>'
				+ '<div name="filePicker" class="webuploader-container"></div></div>');
		webuploader.addbutton.appendTo($queue);

		var userToken = localStorage.getItem("userTonken");
		var lang = localStorage.getItem("lang");
		// WebUploader实例
		webuploader.uploader = WebUploader.create({
			pick : {
				id : '[name="filePicker"]',
				label : messages.selectPhoto,
				multiple: false
			},
			formData : {
				uid : 123
			},
			// dnd: '#dndArea',
			paste : '#uploader',
			// swf: '../../dist/Uploader.swf',
			chunked : false,// 是否要分片处理大文件上传
			chunkSize : 512 * 1024,
			server : Page.contextPath + '/share/upload.do?userToken='+userToken+'&lang='+lang,
			// runtimeOrder: 'flash',

			accept : {
				title : 'Images',
				extensions : 'gif,jpg,jpeg,bmp,png',
				mimeTypes : 'image/*'
			},

			compress : {
				width : 1024,
				height : 768,

				// 图片质量，只有type为`image/jpeg`的时候才有效。
				quality : 60,

				// 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
				allowMagnify : false,

				// 是否允许裁剪。
				crop : false,

				// 是否保留头部meta信息。
				preserveHeaders : false,

				// 如果发现压缩后文件大小比原来还大，则使用原来图片
				// 此属性可能会影响图片自动纠正功能
				noCompressIfLarger : false,

				// 单位字节，如果图片大小小于此值，不会采用压缩。
				//compressSize : 100 * 1024
				compressSize : 0
			},

			duplicate: true,
			// 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
			disableGlobalDnd : true,
			fileNumLimit : 9,
			fileSizeLimit : 20 * 1024 * 1024, // 20 M
			fileSingleSizeLimit : 10 * 1024 * 1024
		});

		webuploader.uploader.on('ready', function() {
			window.uploader = webuploader.uploader;
			// 设置添加图片按钮的高度
			webuploader.addbutton.find('div[id]').height(
					webuploader.addbutton.height());
		});

		// 上传过程中触发，携带上传进度
		webuploader.uploader.onUploadProgress = function(file, percentage) {
			var li = $('#' + file.id), percent = li.find('.progress span');

			percent.css('width', percentage * 100 + '%');
			webuploader.percentages[file.id][1] = percentage;
			updateTotalProgress();
		};

		// 当文件被加入队列以后触发
		webuploader.uploader.onFileQueued = function(file) {
			webuploader.fileCount++;
			webuploader.fileSize += file.size;

			if (webuploader.fileCount === 1) {
				$queue.show();
				$statusBar.show();
				$('#videoToUpload').css('visibility', 'hidden');// 不允许录制视频
			} else if (webuploader.fileCount === 9) {// 已经选择了9张
				setFilePick(false);
			}

			addFile(file);
			setState('ready');
			webuploader.addbutton.find('div[id]').height(
					webuploader.addbutton.height());// 这里又需要重新设置下高度，不晓得为什么
		};

		// 当文件被移除队列后触发
		webuploader.uploader.onFileDequeued = function(file) {
			webuploader.fileCount--;
			webuploader.fileSize -= file.size;

			if (!webuploader.fileCount) {
				$queue.hide();
				setState('pedding');
				$('#videoToUpload').css('visibility', 'visible');
			} else if (webuploader.fileCount < 9) {
				setFilePick(true);
			} else if (webuploader.fileCount == 0) {
				$('#videoToUpload').css('visibility', 'visible');
			}

			removeFile(file);
			//updateTotalProgress();
		};

		webuploader.uploader.on('uploadAccept', function(file, response) {
			if (response.resultCode == 1) {
				$queue.find('img[id="' + file.file.id + '"]').attr('data-src',
						response.data);
				//return true;
			} else {
				return false;
			}
		});

		// 特殊事件all, 这样所有的事件触发都会响应到
		webuploader.uploader.on('all', function(type) {
			switch (type) {
				case 'uploadFinished' :// 当所有文件上传结束时触发
					setState('confirm');
					break;
				case 'startUpload' :// 当开始上传流程时触发
					setState('uploading');
					break;
				case 'stopUpload' :// 当开始上传流程暂停时触发
					setState('paused');
					break;
			}
		});

		// 当validate不通过时，会以派送错误事件的形式通知调用者
		webuploader.uploader.onError = function(code) {
			//alert('Eroor: ' + code);
			if (code == 'Q_EXCEED_SIZE_LIMIT') {
				Page.notice(messages.photoTooLarge+"！");
			} else if (code == 'Q_EXCEED_NUM_LIMIT') {
				Page.notice(messages.tooMuchPhotos+"！");
			}
		};

		// 上传进度
		function updateTotalProgress() {
			var loaded = 0, total = 0, spans = $progress.children(), percent;

			$.each(webuploader.percentages, function(k, v) {
				total += v[0];
				loaded += v[0] * v[1];
			});

			percent = total ? loaded / total : 0;

			spans.eq(0).text(Math.round(percent * 100) + '%');
			spans.eq(1).css('width', Math.round(percent * 100) + '%');
		}

		function setState(val) {
			var stats;

			if (val === webuploader.state) {
				return;
			}
			webuploader.state = val;

			switch (webuploader.state) {
				case 'pedding' :// 等待选择照片
					$queue.hide();
					webuploader.uploader.refresh();
					break;

				case 'ready' :// 已经选择照片，等待上传
					$queue.show();
					webuploader.uploader.refresh();
					break;

				case 'uploading' :// 上传中
					$progress.show();
					webuploader.$upload.text(messages.pause);
					break;

				case 'paused' :// 暂停上传
					$progress.show();
					webuploader.$upload.text(messages.continueUpload);
					break;

				case 'confirm' :// 所有文件上传结束
					$progress.hide();
					webuploader.$upload.text(messages.start);

					stats = webuploader.uploader.getStats();
					if (stats.successNum && !stats.uploadFailNum) {
						setState('finish');
						return;
					}
					break;
				case 'finish' :
					stats = webuploader.uploader.getStats();
					if (stats.successNum) {// 上传成功
						//webuploader.$upload.hide();
						var files = [];
						$($queue.find('img[data-src]')).each(function() {
							files.push($(this).attr('data-src'));
						});
						webuploader.uploadCallback(files);
					} else {
						// 没有成功的图片，重设
						webuploader.state = 'done';
						location.reload();
					}
					break;
			}
		}

		// 当有文件添加进来时执行，负责view的创建
		function addFile(file) {
//			EXIF.getData(file, function() {  
//		            // alert(EXIF.pretty(this));  
//		            EXIF.getAllTags(this);   
//		            //alert(EXIF.getTag(this, 'Orientation'));   
//		            Orientation = EXIF.getTag(this, 'Orientation');  
//		            //return;  
//		    }); 
//			alert(Orientation);
			var li = $('<div class="uploadList" id="' + file.id + '">'
					+ '<div class="pic-info hid"></div><span class="pic-dele hid"></span>'
					+ '<i class="pic-dele iconfont hid">&#xe61f;</i></div>'),

			progress = li.find('p.progress span'), info = li.find('.pic-info'), del = li
					.find('.pic-dele');

			showError = function(code) {
				switch (code) {
					case 'exceed_size' :
						text = messages.sizeToLarge;
						break;
					case 'interrupt' :
						text = messages.paused;
						break;
					default :
						text = messages.tryItLater;
						break;
				}

				info.text(text).css('background-color', '#f00').show();
			};

			if (file.getStatus() === 'invalid') {
				showError(file.statusText);
			} else {
				info.text(messages.Previewing).show();

				webuploader.uploader.makeThumb(file,
						function(error, src) {

							if (error) {
								info.text(messages.toPreview).show();
								return;
							}

							var img = $('<img id="' + file.id + '" src="' + src
									+ '">');
							li.prepend(img);
							info.hide();
							del.show();
						}, _thumbnailWidth, _thumbnailHeight);

				webuploader.percentages[file.id] = [file.size, 0];
				file.rotation = 0;
			}

			// 文件状态变化

			file.on('statuschange', function(cur, prev) {
				if (prev === 'progress') {
					progress.hide().width(0);
				}

				if (cur === 'error' || cur === 'invalid') {
					showError(file.statusText);
					webuploader.percentages[file.id][1] = 1;
				} else if (cur === 'interrupt') {// 上传中断，可续传
					showError('interrupt');
				} else if (cur === 'queued') {// 已经进入队列, 等待上传
					webuploader.percentages[file.id][1] = 0;
				} else if (cur === 'progress') {// 上传中
					progress.css('display', 'block');
				} else if (cur === 'complete') {// 单个上传成功
					li.find('i.pic-dele').hide();
				}

				li.removeClass('state-' + prev).addClass('state-' + cur);
			});

			// 删除文件
			del.on('click', function() {
				webuploader.uploader.removeFile(file);
			});

			webuploader.addbutton.before(li);
		}

		// 负责view的销毁
		function removeFile(file) {
			delete webuploader.percentages[file.id];
			updateTotalProgress();
			$queue.find('#' + file.id).remove();
		}

		// 设置是否允许选择图片
		function setFilePick(can) {
			if (can) {
				webuploader.addbutton.show();
				$('[name="filePicker"] div[id]').css('visibility', 'visible');
			} else {
				webuploader.addbutton.hide();
				$('[name="filePicker"] div[id]').css('visibility', 'hidden');
			}
		}

		webuploader.upload = function(uploadBtn, callback) {
			webuploader.$upload = $(uploadBtn);
			if (uploadBtn.hasClass('disabled') || webuploader.fileCount == 0) {
				return false;
			}
			if (webuploader.state != 'finish') {
				// 不允许再上传
				setFilePick(false);
				// 不允许再删除
				$queue.find('i.pic-dele').hide();

				if (webuploader.state === 'ready') {
					webuploader.uploader.upload();
				} else if (webuploader.state === 'paused') {
					webuploader.uploader.upload();
				} else if (webuploader.state === 'uploading') {
					webuploader.uploader.stop();
				}
				webuploader.uploadCallback = callback;
			} else {
				setState('finish');
			}

		};

		return webuploader;
	}
};

var Slide = function() {

	return {

		show : function(imgs, index) {
			var pswpElement = document.querySelectorAll('.pswp')[0];

			// build items array
			var items = [];
			$(imgs).each(function() {
				var img = new Image();
				img.src = $(this).attr('src');
				items.push({
					src : img.src,
					w : img.width,
					h : img.height
				});
			});
			//console.log(items);
			// define options (if needed)
			var options = {
				// optionName: 'option value'
				// for example:
				index : index
			// start at first slide
			};

			// Initializes and opens PhotoSwipe
			var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default,
					items, options);
			gallery.init();
		}
	}
}();
